import { designComponents } from 'src/use/designComponents';
import { defineComponent, inject, onBeforeUnmount, provide, reactive } from 'vue';

interface Route {
  path?: string;
  hash?: string;
  param?: { [k: string]: string };
}

/**
 * hash路由
 */
function getRoute(): Route {
  let locationHash = window.location.hash || '';
  if (locationHash.charAt(0) === '#') {
    locationHash = locationHash.slice(1);
  }

  const [path, hash] = decodeURIComponent(locationHash).split('#');

  return { path, hash };
}

export const AppNavigator = designComponents({
  name: 'app-navigator',
  providerRefer: true,
  props: {
    defaultPath: String,
  },
  setup({ props, setupContext: context }) {
    const currentRoute = getRoute();

    !currentRoute.path && (currentRoute.path = props.defaultPath);

    const state = reactive({ route: currentRoute });

    const methods = {
      go(path: string) {
        window.location.hash = encodeURIComponent(path);
      },
    };

    const handler = {
      hashchange: () => {
        state.route = getRoute();
      },
    };

    const refer = {
      state,
      methods,
    };

    // 监听hash变化
    window.addEventListener('hashchange', handler.hashchange);

    onBeforeUnmount(() => window.removeEventListener('hashchange', handler.hashchange));

    return {
      refer,
      render: () => (!!context.slots.default ? context.slots.default() : null),
    };
  },
});
